package com.cumulus.MoveCopy;

import java.util.ArrayList;
import java.util.Collections;
import java.util.StringTokenizer;

import com.cumulus.MoveCopy.CreateOwnActivity.MyCount;
import com.cumulus.acceleration.AccAng;
import com.cumulus.acceleration.AccelerationManager;
import com.cumulus.acceleration.Compare;

import android.app.Activity;
import android.content.Intent;
import android.hardware.SensorManager;
import android.media.AudioManager;
import android.media.SoundPool;
import android.media.SoundPool.OnLoadCompleteListener;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v4.app.ShareCompat;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import java.lang.Math;

public class ReplyActivity extends Activity {
	
	private Activity _curActivity;

    private static final String TAG = "ReplyActivity";
    private static final double EMP_CONST = 2.0;
    private AccelerationManager _accelerationManager;
    private int _accuracy;
    protected Integer percentage;
    private SoundPool _soundPool;
    private ArrayList<Integer> _soundID;
    private int _curSoundNum;

	    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
      	Log.d(TAG, "reply activity started");
      	_accuracy = 0;
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.donerecording_activity);

        int current_index =this.getIntent().getExtras().getInt("current_index");
        ((TextView)findViewById(R.id.countdown_timer2)).setText("Player "+(1+current_index)+"'s Turn");

        ((Button)findViewById(R.id.share_button)).setVisibility(View.INVISIBLE);
        _curActivity = this;
        _curSoundNum = 0;
        _soundID = new ArrayList<Integer>();

        _soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
        _soundID.add(_soundPool.load(this, R.raw.sound1, 1));
        _soundID.add(_soundPool.load(this, R.raw.sound2, 1));
        _soundID.add(_soundPool.load(this, R.raw.sound3, 1));
        _soundID.add(_soundPool.load(this, R.raw.sound4, 1));
        _soundID.add(_soundPool.load(this, R.raw.sound5, 1));
        _soundID.add(_soundPool.load(this, R.raw.sound6, 1));

        
		this.setVolumeControlStream(AudioManager.STREAM_MUSIC);       
		
		setTitle("ReplyActivity");


    }
    
    public void onResume() {
    	super.onResume();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        return false;

    }

    
    public void onPause() {
    	super.onPause();
    }
    public void startCountdownForReply(View view) {
    	Log.d(TAG, "reply countdown timer started");
        (new MyCount(4000, 1000)).start();

    }
    
    public class MyCount extends CountDownTimer{
    	
    	private TextView _countdownTimer;
    	
        public MyCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
            _countdownTimer = (TextView)findViewById(R.id.countdown_timer2);

        }

        @Override
        public void onFinish() {

        	_countdownTimer.setText("Go!");
            _countdownTimer = (TextView)findViewById(R.id.countdown_timer2);
        	_accelerationManager = new AccelerationManager((SensorManager)getSystemService(SENSOR_SERVICE), _curActivity);
            startRecordingReply();
        }

        @Override
        public void onTick(long millisUntilFinished) {
            _countdownTimer.setTextSize(60);
        	_countdownTimer.setText(((int) (millisUntilFinished/1000)) + "");
            ((Button)findViewById(R.id.go_stop_button2)).setVisibility(View.INVISIBLE);
        }


    }
    
    public void playSound() {
		_soundPool.play(_soundID.get(_curSoundNum), 1, 1, 1, 0, 1f);
		if(_curSoundNum == _soundID.size() - 1)
			_curSoundNum = 0;
		else
			_curSoundNum ++;
    }
    
	public void startRecordingReply() {
		Log.d(TAG, "record the reply of the second person");

		int timeToReply = this.getIntent().getExtras().getInt("time");
		Log.d(TAG, "time to reply" + timeToReply);
		
		
		// timer for the duration of the first person's recording
        new CountDownTimer(timeToReply * 100, 1000) {

            public void onTick(long millisUntilFinished) {
            	((TextView)findViewById(R.id.time_remaining)).setText("Time remaining: " + millisUntilFinished/1000);
            }

            public void onFinish() {
            	((TextView)findViewById(R.id.time_remaining)).setText("");
        		displayResults();

            }
         }.start();
		
	}
	
	public void shareResults(View view) {

        ShareCompat.IntentBuilder shareIntentBuilder = ShareCompat.IntentBuilder.from(this)
                .setText("I just matched my friend's motion using MotionMatch. Try out this app. It's so cool!")
                .setType("text/plain");
        startActivity(shareIntentBuilder.getIntent());
        
	}
      
	public void displayResults() {
		
		// tally reply with original recording
    	ArrayList<AccAng> replyCoordinates = _accelerationManager.stop();
		ArrayList<String> recordingCoordinatesString =  this.getIntent().getStringArrayListExtra("recordingCoordinates");
		
		ArrayList<AccAng> recordingCoordinates = stringArrayToAccAngArray(recordingCoordinatesString);
		
		Compare comparator = new Compare();
		//float accuracy = (1 - comparator.compare(recordingCoordinates, replyCoordinates)) * 100;
		double accuracy = comparator.adaptiveCompare(recordingCoordinates, replyCoordinates); 

		percentage = (int) (Math.exp((-1) * accuracy * EMP_CONST) * 100);
		Log.d(TAG,"1");
		ArrayList<Integer> players = this.getIntent()
				.getExtras().getIntegerArrayList("player_arr");
		ArrayList<Integer> rounds_played = this.getIntent()
				.getExtras().getIntegerArrayList("rounds_played");
		int current_index = this.getIntent().getExtras()
				.getInt("current_index");
		int round = this.getIntent()
				.getExtras().getInt("num_rounds");
		int recorder_index = this.getIntent().getExtras()
			.getInt("recorder_index");
		Log.d(TAG,"1"+current_index+"    "+percentage);
		
		if (round!=1){
			players.set(current_index, (percentage+players.get(current_index)));
			rounds_played.set(current_index, rounds_played.get(current_index)+1);
		}else{
			players.set(current_index, percentage);
			rounds_played.set(current_index, 1);
		}
		
		Log.d(TAG,"t "+players.toString());
		Log.d(TAG,"rounds "+rounds_played.toString());
		int time = ReplyActivity.this.getIntent().getExtras()
				.getInt("time");
		
		ArrayList<String> recording = ReplyActivity.this.getIntent()
				.getExtras().getStringArrayList("recordingCoordinates");
		
		Intent intent = new Intent(ReplyActivity.this, TransitionActivity.class);
		intent.putExtras(ReplyActivity.this.getIntent().getExtras());
		Boolean a;
		if(current_index==recorder_index){
			intent.putExtra("attempted",true);
			a=true;
		}else{
			intent.putExtra("attempted",false);
			a=false;
		}
		Log.d(TAG, "%" + percentage+"rec "+recorder_index+"cur "+current_index +" "+a );
		
		current_index+=1;
		current_index%=players.size();
		intent.putExtra("time", time);
		intent.putStringArrayListExtra("recordingCoordinates", recording);
		intent.putExtra("current_index", current_index);
		intent.putExtra("recorder_index", recorder_index);
		intent.putExtra("num_rounds", round);
		intent.putExtra("percentage", percentage);
		intent.putIntegerArrayListExtra("player_arr", players);
		startActivity(intent);
		
//		((Button)findViewById(R.id.go_stop_button2)).setText("Exit to home screen");
//		((Button)findViewById(R.id.go_stop_button2)).setOnClickListener(goHomeListener);
//		((Button)findViewById(R.id.go_stop_button2)).setVisibility(View.VISIBLE);
		
		Log.d(TAG, "Accuracy is " + accuracy );
		
		
		_accuracy = percentage;
		
        //add share functionality
        ((Button)findViewById(R.id.share_button)).setVisibility(View.VISIBLE);
		
        

      
	}
	
	
    public void onBackPressed() {
    	Log.d(TAG, "on back pressed");
        Intent intent = new Intent(ReplyActivity.this, MainActivity.class);
        startActivity(intent);
    }
	
	
	public ArrayList<AccAng> stringArrayToAccAngArray(ArrayList<String> stringArray) {
		
		ArrayList<AccAng> accAngList = new ArrayList<AccAng>();
		
		for(String s: stringArray){
			
			String[] newS = s.split(",");
			AccAng newAccAng = new AccAng(Float.parseFloat(newS[0]), Float.parseFloat(newS[1]), Float.parseFloat(newS[2]),
					Float.parseFloat(newS[3]), Float.parseFloat(newS[4]), Float.parseFloat(newS[5]));
			
			accAngList.add(newAccAng);
		}
		
		return accAngList;
		
	}
	

	/*
	 * onClick 
	 * For after a player attempts to match movement
	 * get extras from TransitionActivity
	 * If current player index == original mover index-1,
	 * 
	 * Increment current player index
	 * 
	 */
    View.OnClickListener goHomeListener = new View.OnClickListener() {
        public void onClick(View view) {          	

			ArrayList<Integer> players = ReplyActivity.this.getIntent()
					.getExtras().getIntegerArrayList("player_arr");
			int current_index = ReplyActivity.this.getIntent().getExtras()
					.getInt("current_index");
			int recorder_index = ReplyActivity.this.getIntent().getExtras()
				.getInt("recorder_index");
			int round = ReplyActivity.this.getIntent().getExtras()
					.getInt("num_rounds");
			
			Log.d(TAG, "go back to home page");
			players.set(current_index, _accuracy);



			int time = ReplyActivity.this.getIntent().getExtras()
					.getInt("time");
			ArrayList<String> recording = ReplyActivity.this.getIntent()
					.getExtras().getStringArrayList("recordingCoordinates");

			Intent intent = new Intent(ReplyActivity.this, TransitionActivity.class);
			Log.d(TAG, "go back to home page" + _accuracy);

			intent.putExtra("time", time);
			intent.putStringArrayListExtra("recordingCoordinates", recording);
			intent.putExtra("current_index", current_index);
			intent.putExtra("recorder_index", recorder_index);
			intent.putExtra("num_rounds", round);
			intent.putIntegerArrayListExtra("player_arr", players);
			startActivity(intent);
          }
      };


 }